package com.zhentao.product.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.login.service.TUserService;
import com.zhentao.nlz.project.dto.TFileManageDto;
import com.zhentao.nlz.project.login.TUser;
import com.zhentao.nlz.project.product.TFileManage;
import com.zhentao.nlz.project.product.TTenant;
import com.zhentao.product.mapper.TFileManageMapper;
import com.zhentao.product.properties.MinioProperties;
import com.zhentao.product.service.TFileManageService;
import com.zhentao.product.service.TTenantService;
import com.zhentao.utils.Result;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
* @author 不.凌
* @description 针对表【t_file_manage(文件管理表)】的数据库操作Service实现
* @createDate 2024-09-22 21:09:18
*/
@Service
public class TFileManageServiceImpl extends ServiceImpl<TFileManageMapper, TFileManage>
        implements TFileManageService {
    @Autowired
    private TUserService tUserService;
    @Autowired
    private TTenantService tTenantService;
    @Autowired
    private MinioProperties minioProperties;
    private Long fileSize;
    private String avatar;
    private String bucketName;
    private String type;

    @Override
    public Result fileList() {
        TUser user = tUserService.getUsers();
        System.err.println(user);
        List<TFileManage> list = this.list(Wrappers.<TFileManage>lambdaQuery()
                .eq(user.getTenantId() != 0, TFileManage::getTenantId, user.getTenantId()));
        for (TFileManage tFileManage : list) {
            TUser one = tUserService.getOne(Wrappers.<TUser>lambdaQuery()
                    .eq(tFileManage.getCreateUser() != null, TUser::getUserId, tFileManage.getCreateUser()));
            tFileManage.setCreateName(one.getUsername());
            TTenant one1 = tTenantService.getOne(Wrappers.<TTenant>lambdaQuery()
                    .eq(tFileManage.getTenantId() != null, TTenant::getId, tFileManage.getTenantId()));
            tFileManage.setTenantName(one1.getName());
        }
        return Result.success(list);
    }

    @Override
    public String upload(MultipartFile file) {
        InputStream inputStream = null;
        try {
            //minio上传文件
            //获取minio客户端连接
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioProperties.getEndpoint())
                    .credentials(minioProperties.getUsername(), minioProperties.getPassword())
                    .build();
            //校验存储桶是否存在bucket
//        minioClient.
            //minio上传文件
//            FileInputStream fileInputStream = new  FileInputStream("D:\\apple.png");
            inputStream = file.getInputStream();
            //文件名称
            String originalFilename = file.getOriginalFilename();

            String fileName = IdUtil.simpleUUID() + originalFilename;
            int dotIndex1 = fileName.lastIndexOf('.');
            String result1 = fileName.substring(0, dotIndex1);
            System.out.println(result1);
            bucketName = result1;
            //文件的上传属性参数
            PutObjectArgs build = PutObjectArgs.builder()
                    .bucket(minioProperties.getBucketName())   //存储桶
                    .object(fileName)  //文件名
                    .stream(inputStream, file.getSize(), -1)  //文件流，文件大小，分片大小
                    .build();
            minioClient.putObject(build);

            System.out.println("上传成功");
            fileSize = file.getSize();
            System.out.println("文件大小：" + file.getSize());
            System.err.println(minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" + fileName);
            avatar = minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" + fileName;
            String s = minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" + fileName;
            int dotIndex = s.lastIndexOf('.');
            String result = s.substring(dotIndex + 1);
            System.out.println(result);
            type = result;
            System.out.println("type----------" + type);
            System.out.println("bucketName----------" + bucketName);
            System.out.println("avatar----------" + avatar);
            System.out.println("fileSize----------" + fileSize);
            //返回的文件名必须是全路径：minio服务地址+bucket+自定义命名的文件名
            return minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" + fileName;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //释放资源
            try {
                inputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public Result delete(Integer id) {
        boolean b = this.removeById(id);
        return b ? Result.success("成功") : Result.error("失败");
    }

    @Override
    public Result updateDataById(TFileManage fileManage) {
        fileManage.setUpdateTime(new DateTime());
        TUser user = tUserService.getUsers();
        fileManage.setUpdateUser(user.getUserId());
        boolean b = this.updateById(fileManage);
        return b ? Result.success("成功") : Result.error("失败");
    }

    @Override
    public Result saveData(TFileManage fileManage) {
        fileManage.setCreateTime(new DateTime());
        TUser user = tUserService.getUsers();
        fileManage.setCreateUser(user.getUserId());
        fileManage.setTenantId(user.getTenantId());
        fileManage.setOriginal(avatar);
        fileManage.setFileSize(fileSize);
        fileManage.setBucketName(bucketName);
        fileManage.setType(type);
        boolean b = this.save(fileManage);
        return b ? Result.success("成功") : Result.error("失败");
    }

}




